<?php
//==============================================================================
//nabtonData.php
//Desc: Used for rendering measurement data for graphs 
//=============================================================================
session_start();

require_once('dataManager/definitions.php');
require_once('dataManager/DataManager.php');

//Check if logged in -> if not die
if($_SESSION['valid_login'] == false)
{
	die();
}


// Main program ======================
$action = $_POST['action'];
switch($action)
{
	case "fetchApplications":
		$uid = $_SESSION['uid'];
		$dbM = new DataManager(DB_USER, DB_PASSWORD, "localhost", NB_DATABASE_ADMIN);
		$dbM->selectAllFromTable(NB_ADMIN_TABLE_APPLICATIONS, NB_ADMIN_APPLICATIONS_COLUMN_OWNERID."=$uid".
                                 " OR ".NB_ADMIN_APPLICATIONS_COLUMN_SHARED."=1");  

		$ii = 0;
		while ($data = $dbM->retrieveResult())
		{
		    $dataArray[$ii] = array($data[NB_ADMIN_APPLICATIONS_COLUMN_APPID],
                                    $data[NB_ADMIN_APPLICATIONS_COLUMN_TITLE],
                                    $data[NB_ADMIN_APPLICATIONS_COLUMN_CHARTTYPE]); 
		    $ii++;
		}
		
		echo json_encode($dataArray); 

	   break;
    case "fetchValidDates":
        $appid = $_POST['appId'];

        //fetch sids		
        $dbM_A = new DataManager(DB_USER, DB_PASSWORD, "localhost", NB_DATABASE_ADMIN);
    
        $dbM_A->selectAllFromTable(NB_ADMIN_TABLE_APPSTREAMLINK, NB_ADMIN_APPSTREAMLINK_COLUMN_APPID."=$appid");
        
        while ($data = $dbM_A->retrieveResult())
        {
            $sids[]= $data[NB_ADMIN_APPSTREAMLINK_COLUMN_SID];
        }
    
        $dbM_C = new DataManager(DB_USER, DB_PASSWORD, "localhost", NB_DATABASE_COLLECTOR);
    
        if(count($sids)>0)
        {
            //Fetch dates for every sid
            foreach ($sids as $sid)
            {
                $dbM_C->selectDistinctDates(NB_COLLECTOR_TABLE_DATA_PREFIX.$sid, NB_GENERAL_COLUMN_TIMESTAMP);

                $intss = $dbM_C->retrieveNumberOfResults();
                while ($data = $dbM_C->retrieveResult())
                {
                    $dateArray[] = $data['dates'];
                }
            }
            $dateArray_final = array_unique($dateArray);
        }
        else
        {
            $dateArray_final = 0;
        }

        echo json_encode($dateArray_final); 
	   break; 
    
	case "fetchAppData":
        if (isset($_POST['from']) && isset($_POST['to']) && isset($_POST['appId']))
        {      
            $appId = $_POST['appId'];
            $from = round($_POST['from']/1000);
            $to   = round($_POST['to']/1000);
        }
        elseif (isset($_POST['from']) && isset($_POST['appId']))
        {
            $appId = $_POST['appId'];
            $from = round($_POST['from']/1000);
            $to   = $from + 86400; // 86400 seconds/day
        }
        else
        {
            json_encode($dataArray); 
            die();
        }
    
        if (isset($_POST['resolution']))
        {
            $resolution = (int)$_POST['resolution'];
            
            //Make sure resolution does not exceed the alternatives
            if ($resolution > 800)
            {
                $resolution = 200;
            }
        }
        else
        {
            $resolution = 200;
        }
             
        //Fetch sids		
        $dbM_A = new DataManager(DB_USER, DB_PASSWORD, "localhost", NB_DATABASE_ADMIN);
    
        $dbM_A->selectAllFromTable(NB_ADMIN_TABLE_APPSTREAMLINK, NB_ADMIN_APPSTREAMLINK_COLUMN_APPID."=$appId");
        
        while ($data = $dbM_A->retrieveResult())
        {
            $sids[]= $data[NB_ADMIN_APPSTREAMLINK_COLUMN_SID];
        }
    
        $numSids = count($sids);
        
        //fetch sid data
		$dbM = new DataManager(DB_USER, DB_PASSWORD, "localhost", NB_DATABASE_COLLECTOR);
    
        for($i=0; $i<$numSids; $i++)
        {
            // TODO add limit to owner_id + limit time? For now all with sid          
            $dbM->selectAllFromTable(NB_COLLECTOR_TABLE_DATA_PREFIX.$sids[$i], "ts BETWEEN FROM_UNIXTIME($from) AND FROM_UNIXTIME($to)"); 

            while($data = $dbM->retrieveResult())
            {
                $time[]   = strtotime($data[NB_GENERAL_COLUMN_TIMESTAMP]); 
                $values[] = (float)$data[NB_COLLECTOR_DATA_COLUMN_VALUE]; 
            }
           
            $currentNumDataPoints = count($time);
            $divider = ceil((float)$currentNumDataPoints/(float)$resolution);
   
            for ($ii=0; $ii<$currentNumDataPoints; $ii=$ii+$divider) 
            {
                $timeFinal[] = $time[$ii];
                $valuesFinal[] = $values[$ii];
            }
            
            $sidData[] = $timeFinal;
            $sidData[] = $valuesFinal;
            $numberOfDataPoints[] = $currentNumDataPoints;
                 
            unset($time);
            unset($values);
            unset($timeFinal);
            unset($valuesFinal);
            
        }
        $sidData[] = $numberOfDataPoints;
        echo json_encode($sidData); 
	   break;
}





?>
